package com.ericsson.resourceplanner.dao.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;












import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.transaction.Transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ericsson.resourceplanner.dao.ChangeRoleDAO;
import com.ericsson.resourceplanner.dao.entity.EmpDetails;
import com.ericsson.resourceplanner.dao.entity.EmployeeRole;
import com.ericsson.resourceplanner.dao.entity.Role;
import com.ericsson.resourceplanner.dto.EmployeeDtlsVO;



@Repository
public class ChangeRoleDAOImpl implements ChangeRoleDAO {
	
	
	@PersistenceContext
	EntityManager entityManager;
	
	
	/*@Autowired
	EntityManagerFactory factory;*/
	
	@SuppressWarnings("unchecked")
	public List<EmpDetails> fetchEmployeeDetails(){
	
		List<EmpDetails> employee_list = null;
        
	  try{
	//	employee_list = factory.createEntityManager().createNamedQuery("EmpDetails.findAll",EmpDetails.class).getResultList();
		                      
	    employee_list  = entityManager.createNamedQuery("EmpDetails.findAll",EmpDetails.class).getResultList();
				
        }
	  
	    catch(Exception e){
	    	e.printStackTrace();
	    }
	
	
		return employee_list ;
		
		
	
	}
	
	public List<Role> fetchRoleDetails(){
		
		
		List<Role> role_list = new ArrayList<Role>();
		try{
		
		String query =  "select r.id , r.role_Name from Role r";
		
		//  List<Object[]>  list = (List<Object[]>)(List<?>)factory.createEntityManager().createNativeQuery(query).getResultList();
		
		List<Object[]>  list = (List<Object[]>)(List<?>)entityManager.createNativeQuery(query).getResultList();
		
		 if(list!=null && list.size()>0){
			
			 for(int i = 0 ; i<list.size(); i++){
				 Role role = new Role(); 
				 Long long_obj = new Long(list.get(i)[0].toString()); 
				 role.setId(long_obj.longValue());
				 role.setRoleName((String)list.get(i)[1]);
				 role_list.add(role);
				// System.out.println("id"+list.get(i)[0]+"name:"+list.get(i)[1]);
			 }
		 }
		
		
		}
		
		catch(Exception e){
			e.printStackTrace();
		}
		
		return role_list;
		
	}
	
	public static void main(String[] args) {
		
		EmployeeDtlsVO evo = new EmployeeDtlsVO();
		List<Long> roles = new ArrayList<Long>();
		roles.add(3L);
		evo.setEmp_rolelist(roles);
		
		evo.setId(2);
		ApplicationContext context = new ClassPathXmlApplicationContext("root-context.xml","servlet-context.xml");
		ChangeRoleDAOImpl dao = context.getBean("changeRoleDAOImpl",ChangeRoleDAOImpl.class);
		dao.updateRole(new EmployeeDtlsVO[]{evo});
		
		
		
		
	}
	
    @Transactional(propagation=Propagation.REQUIRES_NEW)
    
	@Override
	public void updateRole(EmployeeDtlsVO[] emp) {
		// TODO Auto-generated method stub
		
     try{
    	
		int id ;
		EmpDetails emp_obj = null;
	  //  EntityManager entity = factory.createEntityManager() ;
	        
		Set<EmployeeRole> emp_set = new HashSet<EmployeeRole>();

		for(EmployeeDtlsVO employeeDtlsVO: emp){
			
			id =employeeDtlsVO.getId();
			
			emp_obj = entityManager.find(EmpDetails.class, Integer.toString(id));
			System.out.println(emp_obj);
			 Set<EmployeeRole>  set = emp_obj.getEmployeeRoles();
			 for(EmployeeRole er:set)
			 {
				 entityManager.remove(er);
				 
			 }
			 //entityManager.refresh(emp_obj);
			 set.clear();
			 //entityManager.refresh(emp_obj);
			 //emp_obj = entityManager.find(EmpDetails.class, Integer.toString(id));
			 
			 System.out.println("size------------------------------"+set.size());
//			    for(EmployeeRole  employeeRole :set){
//			     long r_id =	employeeRole.getId();
//			     Query   query = entityManager.createNativeQuery ("delete from EMPLOYEE_ROLE  where ID= ?");
//			     query.setParameter(1, r_id);
//			     int i = query.executeUpdate();
//			     System.out.println("return:"+i);
//			     }
		  	
			
			for(Long role : employeeDtlsVO.getEmp_rolelist()){
            
			Role rule =  entityManager.find(Role.class, role);
			
			EmployeeRole er = new EmployeeRole();
			er.setRole(rule);
			er.setEmployee(emp_obj);
		//	System.out.println("Role id, RoleName:"+rule.getId()+","+rule.getRoleName());
//			Long role_id  =  rule.getId();
//			String role_name = rule.getRoleName();
			
//			String query = "insert into EMPLOYEE_ROLE (ID,EMPLOYEE_ID,ROLE_ID) values(EMPLOYEE_ROLE_SEQUENCE.nextval,"+id+","+role+")";
//			entityManager.createNativeQuery(query).executeUpdate();
			set.add(er);
           
			}
			emp_obj.setEmployeeRoles(set);
			System.out.println("size 111---------------------"+set.size());
			
		    entityManager.merge(emp_obj);
		    entityManager.flush();
		}
	
     }
     
     catch(Exception e){
    	 e.printStackTrace();
     }
		
	}
    
    

}
